package com.mobilesales.android.adapters;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.ImageView;
import android.widget.TextView;

import com.mobilesales.android.R;
import com.mobilesales.android.infrastructure.ProductCategoryItem;
import com.mobilesales.android.util.CustomFilter;

public class ProductCategoryAdapter extends ArrayAdapter<ProductCategoryItem> {

	private List<ProductCategoryItem> items = null;
	int layoutID;
	Context context;

	public ProductCategoryAdapter(Context context, int textViewResourceId,
			List<ProductCategoryItem> objects) {
		super(context, textViewResourceId, objects);
		items = new ArrayList<ProductCategoryItem>(objects);
		layoutID = textViewResourceId;
		this.context = context;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View v = convertView;
		if (v == null) {
			LayoutInflater vi = (LayoutInflater) getContext().getSystemService(
					Context.LAYOUT_INFLATER_SERVICE);
			v = vi.inflate(layoutID, null);
		}

		ProductCategoryItem item = null;
		if (position >= 0 && position < this.getCount()) {
			item = this.getItem(position);
		}

		if (item != null) {
			/*if (position % 2 == 0) {
				v.setBackgroundResource(R.drawable.button_blue_select);
			} else {
				v.setBackgroundResource(R.drawable.button_gray_select);
			}*/
			ImageView icon = (ImageView) v.findViewById(R.id.productCatIcon);
			TextView nameField = (TextView) v.findViewById(R.id.productCatName);
			TextView priceField = (TextView) v.findViewById(R.id.priceTxt);

			if (item.isCategory()) {
				icon.setImageResource(R.drawable.folder_icon);
				nameField.setText(item.getCategory().Name);
				priceField.setVisibility(View.GONE);
			} else {
				icon.setImageResource(R.drawable.product_icon);
				nameField.setText(item.getProduct().Name);
				priceField.setText(String.format("%1$,.2f",
						item.getProduct().Price));
			}
		}

		return v;
	}

	@Override
	public Filter getFilter() {
		return new CustomFilter<ProductCategoryItem>(this, items) {

			@Override
			protected boolean fits(String query, ProductCategoryItem item) {
				String searchStr = null;
				if (item.isCategory())
					searchStr = item.getCategory().Name;
				else
					searchStr = item.getProduct().Name;
				Log.i("fits", searchStr + " " + query);
				if (searchStr.toLowerCase().contains(query.toLowerCase())) {
					return true;
				}
				return false;
			}

		};
	}

}
